// pages/patrolLog/patrolLog.js
const app = getApp()
const util = require('../../utils/util.js')
var BLELocker = require("../../utils/BLELocker.js")
var openLockUtil = require("openLock.js")
const lbbService = require('../service/service.js')

var blueConStatHandler = require("../../utils/blueConStatHandler.js")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    hospitalId: '',
    activeTab: '0',
    sysProblemList: [],
    serProblemList: [],
    scanning: false,
    list:[]
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    console.log('options', options)
    this.setData({
      scrollHeight: app.getScrollHeight(0)
    })
    let that = this
    if (options.hospitalId) {
      wx.setStorageSync('hospitalId', options.hospitalId)
      that.setData({
        hospitalId: options.hospitalId,
        hospitalName: options.hospitalName,
      })
    } else {
      let hospitalId = wx.getStorageSync('hospitalId')
      that.setData({
        hospitalId,
      })
    }
    that.getLocation(that.isMatch)
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    if (!that.data.scanning) {
      lbbService.getInspectionStat({ hospitalId: parseInt(that.data.hospitalId) },function(res){
        lbbService.getAllQuestions({ hospitalId: parseInt(that.data.hospitalId) }, function (res) {
          that.setData({
            serProblemList: res.data.submitFeedbackMap,
          })
        })
        that.setData({
          hospitalPatrolInfo: res.hospitalPatroInfo,
          chairList: res.hospitalPatroInfo.chairList,
          carList: res.hospitalPatroInfo.stretcherList,
          list:res.hospitalPatroInfo.getHospitalEquTyp,
          otherList:res.hospitalPatroInfo.getHospitalMap,
        })
        wx.hideLoading()
        let flag = that.patrolStatusCheck()
        that.setData({
          flag: flag
        })
      })
    }
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.removeStorageSync('hospitalId')
  },
  toProblemItem: function(e){
    let that = this
    console.log(e)
    let num = e.currentTarget.dataset.num
    if(num ==0 ){
      return
    }
    let name = e.currentTarget.dataset.name
    let id = e.currentTarget.dataset.id
    let hospitalId = that.data.hospitalId
    wx.navigateTo({
      url: '../problemItem/problemItem?questionName=' + name + '&questionId=' + id + '&hospitalId=' + hospitalId,
    })
  },
  getLocation: function(_callback){
    // 微信获得经纬度
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log('获取经纬度成功', res)
        app.globalData.header.lat = parseFloat(res.latitude)
        app.globalData.header.lng = parseFloat(res.longitude)
        if (_callback){
          _callback()
        }
      },
      fail: function (res) {
        console.log('获取经纬度fail', res)
      }
    })
  },
  toggleTab: function (e) {
    let activeTab = e.currentTarget.dataset.activenum
    this.setData({
      activeTab: activeTab
    })
  },
  toLostList: function () {
    let that = this
    wx.navigateTo({
      url: '/pages/mayLostEquipList/mayLostEquipList?mayLostList=' + JSON.stringify(that.data.hospitalPatrolInfo.mayLost.mayLostDetail) + '&hospitalId=' + that.data.hospitalId + '&hospitalName=' + that.data.hospitalName,
    })
  },
  patrolComplete: function () {
    let that = this
    if (that.patrolStatusCheck()) {
      lbbService.completeInspect({ hospitalId: parseInt(that.data.hospitalId)},function(res){
        that.getLocation()
        that.personalModal.showModal('巡检全部完成，辛苦您了！', function () {
          wx.navigateBack({
            delta: 1
          })
        })
      })
    } else {
      that.personalModal.showModal('有待巡检的桩位！')
    }
  },
  patrolStatusCheck: function () {
    let currentInfo = this.data.hospitalPatrolInfo.pile
    for (let i = 0; i < currentInfo.length; i++) {
      for (let j = 0; j < currentInfo[i].pileListList.length; j++) {
        if (currentInfo[i].pileListList[j].uurInspected== 0) {
          return false
        }
      }
    }
    return true
  },
  /*开锁*/
  scanOpenLock:function(){
    let that = this;
    that.scan(that.openLock);
  },
  /*扫码巡检桩位并跳转到桩详情页面*/
  patrolPile:function(){
    let that = this;
    that.data.scanning = true;
    wx.scanCode({
      success(res) {
        var qrc = '';
        if (res.result.indexOf(util.CONST_DATA.DEVICE_QRCODE_URL_PREFIX) == 0) {
          var rst = res.result.split('/');
          qrc = rst[rst.length - 1];
          that.data.scan_qrc = qrc;
        }
        else{
         var str = res.result.split(':')
         var strn = ''
         str.forEach(item=>{return strn+= item})
          that.data.scan_qrc = strn;
        }
        that.data.scanning = false;
        lbbService.getMacId({
          markCode: that.data.scan_qrc,
          system: getApp().globalData.systemInfo ? getApp().globalData.systemInfo.system : 'ios'
        }, function (result) {
          if (result.macId) {
            that.data.newConFlg = result.newConFlg;
            that.data.curIsDirectCon = res.curIsDirectCon;
            that.data.pileCode = result.pileId;
            that.data.macId = result.macId;
            that.data.pileType = result.categoryId;
            that.data.hospitalId = result.lbmId
            wx.navigateTo({
              url: '../pileOperate/pileItem/pileItem?macId=' + result.macId + '&pileCode=' + result.pileId + '&hospitalId=' + that.data.hospitalId + '&pileType=' + result.categoryId + '&newConFlg=' + result.newConFlg
            })
          } else {
            wx.showToast({
              title: '获取mac失败',
            })
          }
        })
      },
      fail(res) {
        that.data.scanning = false;
      }
    })
  },
  /*扫码并连接*/
  scan: function(_callback){
    var that = this;
    that.data.scanning = true;
    wx.scanCode({
      success(res) {
        var qrc = '';
        if (res.result.indexOf(util.CONST_DATA.DEVICE_QRCODE_URL_PREFIX) == 0) {
          var rst = res.result.split('/');
          qrc = rst[rst.length - 1];
          that.data.scan_qrc = qrc;
        }else{
          var str = res.result.split(':')
          var strn = ''
          str.forEach(item=>{return strn+= item})
           that.data.scan_qrc = strn;
         }
        that.data.scanning = false;
        lbbService.getMacId({ 
          markCode: that.data.scan_qrc,
          system: getApp().globalData.systemInfo ? getApp().globalData.systemInfo.system : 'ios'
        },function(res){
          if (res.macId) {
            that.data.newConFlg = res.newConFlg;
            that.data.curIsDirectCon = res.curIsDirectCon;
            that.data.pileCode = res.pileId;
            that.data.macId = res.macId;
            that.data.wxDeviceId = getApp().getDeviceId(res.macId);
            that.data.pileType = res.categoryId;
            that.getConnect(res.macId, _callback);
            that.data.hospitalId = res.lbmId
          } else {
            wx.showToast({
              title: '获取mac失败',
            })
          }
        })
      },
      fail(res) {
        that.data.scanning = false;
      }
    })
  },
  hideModal1() {
    this.setData({
      modal: {
        modal_show: false,
        confirm: false,
        retry95: false,
        retryConnect: false
      }
    })
  },
  /**
   * 重试95
   */
  retry95() {
    let that = this;
    that.hideModal1();
    that.setData({
      loading_show: true,
      loading_desc: "数据读取中"
    });
    BLELocker.send95Command(function (isSuccess) {
      if (isSuccess == false) {
        that.getConnect(that.data.macId)
      } else { }
    })
  },
  /**
   * 重试蓝牙连接
   */
  retryConnect() {
    console.log('retryConnect');
    let that = this;
    that.hideModal1();
    that.setData({
      loading_show: true,
      loading_desc: "设备连接中"
    });
    that.getConnect(that.data.macId);
  },
  getConnect: function (macId, _callback) {
    let that = this;
    that.setData({
      loading_show:true,
      loading_desc:'设备连接中...'
    })
    if (that.data.newConFlg) {
      BLELocker.newConnect('DK' + macId, function (status, data) {
        blueConStatHandler.handleStatus(status, data, that, _callback, true)
      }, 0, false, null, null, that);
    } else {
      BLELocker.directConnect('DK' + macId, function (status, data) {
        blueConStatHandler.handleStatus(status, data, that, _callback, true)
      }, 0, false, null, null, that);
    };
  },
  /*开锁*/
  openLock() {
    let that = this;
    if (that.data.data_95) {
      that.setData({
        loading_desc:'正在开锁...'
      })
      lbbService.openLock({
        rfId: that.data.data_95.rfid,
        mac: that.data.macId,
        costTime: that.data.data_95.costTime,
        //insertSwitch: that.data.data_95.
      },function(res){
        BLELocker.send85Command(function (isSuccess) {
          
          if (isSuccess == false) {
            that.setData({
              loading_show: false,
            });
            wx.showToast({
              title: '开锁失败请重试',
              image:'/images/gantan.png',
              duration:2000
            })
          } else {
            setTimeout(() => {
              that.setData({
                loading_show: false,
              });
            },4000)
          }
        });
      })
    } else {
      wx.showToast({
        title: '连接失败请重试',
        image: '/images/gantan.png'
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成 
   */
  onReady: function() {
    this.personalModal = this.selectComponent("#personalModal")
  },

  
  isMatch: function(){
    let that = this
    lbbService.getHospitalLngAndLat({ hospitalId: parseInt(that.data.hospitalId) },function(res){
      that.setData({
        isMatch: res.data
      })
    })
  },
  notMatch:function(){
    let that = this
    let text = '检测到您不在' + that.data.hospitalPatrolInfo.basicInfo.hospitalName + '附近，请直接点击桩列表查看桩信息'
    that.personalModal.showModal(text)
  }
})